from base.web import SHandler, BaseHandler
from urllib import parse, request
import xml.etree.ElementTree as ET
import requests
# appid = 'wxeaa6b7feffe5d8a4'
# secret = 'b5408a55b1eed376ad35421e9bb317e8'
# token = 'pengjinyl'
def w(url, data):
    data = parse.urlencode(data).encode(encoding='UTF8')
    req = request.Request(url=url, data=data)
    res = request.urlopen(req).read()
    return eval(res)

class wechat_in(BaseHandler):
    def get(self):
        echostr = self.get_argument('echostr', '')
        self.write(echostr)
    def post(self):
        data = ET.fromstring(self.request.body)
        openid = '\'' + data.find('FromUserName').text + '\''
        self.write('success')

# class wechat_login(BaseHandler):
#     def post(self):
#         global appid
#         global secret
#         try:
#             user = requests.get('''https://api.weixin.qq.com/cgi-bin/user/info?
#                 access_token={0}&openid={1}&lang=zh_CN'''.format(self.access_token, self.openid))
#             if 
#         except:
#             self.access_token = requests.get('''https://api.weixin.qq.com/cgi-bin/token?
#                 grant_type=client_credential&appid={0}&secret={1}'''.format(appid, secret))['access_token']

#         self.insert_sql('insert into pj_user(openid, name, info, headimg) values ({params})'.format(params = params))
        
wechat_url = [
    (r'/api/wechat_in', wechat_in),
    # (r'/api/wechat_login', wechat_login),
]